{% extends 'layout/pure_manage.html' %}
{% load dashboard %}
{% load issues %}
{% block title %}{% endblock %}

{% block css %}
    <style>

        .switch input {
            opacity: 0;
            width: 0;
            height: 17px;
        }

        input:checked + .slider {
            background-color: #2196F3;
        }

        input:focus + .slider {
            box-shadow: 0 0 1px #2196F3;
        }

        input:checked + .slider:before {
            -webkit-transform: translateX(26px);
            -ms-transform: translateX(26px);
            transform: translateX(26px);
        }

        .table-right > tbody > tr > td.label-left {
            width: 90px;
        }

        .table-right > tbody > tr > td {
            border: 0;
        }

        .status-count .count {
            font-size: 25px;
        }

        .status-count a {
            text-decoration: none;
        }

    </style>

{% endblock %}

{% block content %}
    <div class="container-fluid" style="margin-top: 20px">
        <div class="row">
            <ul class="col-md-12" style="padding-top: -20px">
                <li class="col-md-10"></li>
                <li class="col-md-2" role="presentation">
                    <a href="{% url 'export_kanban' project_id=request.web.project.id %}?csrfmiddlewaretoke="
                       +{{ csrf_token }}>导出看板</a>
                </li>
            </ul>


            <div id="kanban">
                <div class="col-md-2">
                    <div class="panel panel-default">
                        <div class="panel-heading">
                            <i class="fa fa-columns" aria-hidden="true"></i>
                            需求/任务池
                        </div>
                        <div class="panel-body"
                             style="word-wrap:break-word;word-break:break-all;height: 650px;min-height: 55.3vh;display: block;overflow-y: scroll;"
                             id="storyTaskPool" name="dragDropDiv">
                            {% if pool_list %}
                                {% for p in pool_list %}
                                    <!--kanban-->
                                    <li style="cursor: grab" id={{ p.3 }}-{{ p.0 }} value={{ p.8 }}
                                            class="grab-item
                                        alert{% if p.6 == 'bug' %}
                                        alert-danger{% else %}
                                        alert-info{% endif %}"
                                    role="alert">
                                    <p>
                                        <a href="{{ p.4 }}">[{{ p.3 }}]</a>
                                        -{{ p.1 }}</p>


                                    {% if p.6 == 'bug' %}
                                        <span class="badge">Bug</span>
                                    {% endif %}
                                    </li>
                                {% endfor %}
                            {% endif %}
                        </div>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="panel panel-default">
                        <div class="panel-heading">
                            <i class="fa fa-columns" aria-hidden="true"></i>
                            确认分析/分配中
                        </div>
                        <div class="panel-body"
                             style="word-wrap:break-word;word-break:break-all;height: 650px;min-height: 55.3vh;display: block;overflow-y: scroll;"
                             id="confirmAssignIng" name="dragDropDiv">
                            <!--kanban-->
                            {% if confirm_list %}
                                {% for c in confirm_list %}
                                    <!--kanban-->
                                    <li style="cursor: grab" id={{ c.3 }}-{{ c.0 }} value={{ c.8 }}
                                            class="grab-item
                                        alert
                                            {% if c.6 == 'bug' %}
                                        alert-danger{% else %}
                                        alert-info{% endif %}"
                                    role="alert">
                                    <p>
                                        <a href="{{ c.4 }}">[{{ c.3 }}]</a>
                                        -{{ c.1 }}</p>

                                    {% if c.6 == 'bug' %}
                                        <span class="badge">Bug</span>
                                    {% endif %}
                                    </li>
                                {% endfor %}
                            {% endif %}
                        </div>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="panel panel-default">
                        <div class="panel-heading">
                            <i class="fa fa-columns" aria-hidden="true"></i>
                            开发中
                        </div>
                        <div class="panel-body"
                             style="word-wrap:break-word;word-break:break-all;height: 650px;min-height: 55.3vh;display: block;overflow-y: scroll;"
                             id="developing" name="dragDropDiv">
                            <!--kanban-->
                            {% if developing_list %}
                                {% for de in developing_list %}
                                    <!--kanban-->
                                    <li style="cursor: grab" id={{ de.3 }}-{{ de.0 }} value={{ de.8 }}
                                            class="grab-item
                                        alert
                                            {% if de.6 == 'bug' %}
                                        alert-danger{% else %}
                                        alert-info{% endif %}"
                                    role="alert">
                                    <p>
                                        <a href="{{ de.4 }}">[{{ de.3 }}]</a>
                                        -{{ de.1 }}</p>


                                    {% if de.6 == 'bug' %}
                                        <span class="badge">Bug</span>
                                    {% endif %}
                                    </li>
                                {% endfor %}
                            {% endif %}
                        </div>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="panel panel-default">
                        <div class="panel-heading">
                            <i class="fa fa-columns" aria-hidden="true"></i>
                            已完成/测试中
                        </div>
                        <div class="panel-body"
                             style="word-wrap:break-word;word-break:break-all;height: 650px;min-height: 55.3vh;display: block;overflow-y: scroll;"
                             id="doneAndTesting" name="dragDropDiv">
                            <!--kanban-->
                            {% if done_list %}
                                {% for d in done_list %}
                                    <!--kanban-->
                                    <li style="cursor: grab" id={{ d.3 }}-{{ d.0 }} value={{ d.8 }}
                                            class="grab-item
                                        alert{% if d.6 == 'bug' %}
                                        alert-danger{% else %}
                                        alert-info{% endif %}"
                                    role="alert">
                                    <p>
                                        <a href="{{ d.4 }}">[{{ d.3 }}]</a>
                                        -{{ d.1 }}</p>

                                    {% if d.6 == 'bug' %}
                                        <span class="badge">Bug</span>
                                    {% endif %}
                                    </li>
                                {% endfor %}
                            {% endif %}
                        </div>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="panel panel-default">
                        <div class="panel-heading">
                            <i class="fa fa-columns" aria-hidden="true"></i>
                            待发布/发版(DEV)
                        </div>
                        <div class="panel-body"
                             style="word-wrap:break-word;word-break:break-all;height: 650px;min-height: 55.3vh;display: block;overflow-y: scroll;"
                             id="toBeRelease" name="dragDropDiv">
                            <!--kanban-->
                            {% if dev_list %}
                                {% for dev in dev_list %}
                                    <!--kanban-->
                                    <li style="cursor: grab" id={{ dev.3 }}-{{ dev.0 }} value={{ dev.8 }}
                                            class="grab-item
                                        alert{% if dev.6 == 'bug' %}
                                        alert-danger{% else %}
                                        alert-info{% endif %}"
                                    role="alert">
                                    <p>
                                        <a href="{{ dev.4 }}">[{{ dev.3 }}]</a>
                                        -{{ dev.1 }}</p>

                                    {% if dev.6 == 'bug' %}
                                        <span class="badge">Bug</span>
                                    {% endif %}
                                    </li>
                                {% endfor %}
                            {% endif %}
                        </div>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="panel panel-default">
                        <div class="panel-heading">
                            <i class="fa fa-columns" aria-hidden="true"></i>
                            已发布/发版(PROD)
                        </div>
                        <div class="panel-body"
                             style="word-wrap:break-word;word-break:break-all;height: 650px;min-height: 55.3vh;display: block;overflow-y: scroll;"
                             id="released" name="dragDropDiv">
                            <!--kanban-->
                            {% if prod_list %}
                                {% for prod in prod_list %}
                                    <!--kanban-->
                                    <li style="cursor: grab" id={{ prod.3 }}-{{ prod.0 }} value={{ prod.8 }}
                                            class="grab-item
                                        alert{% if prod.6 == 'bug' %}
                                        alert-danger{% else %}
                                        alert-info{% endif %}"
                                    role="alert">
                                    <p>
                                        <a href="{{ prod.4 }}">[{{ prod.3 }}]</a>
                                        -{{ prod.1 }}</p>

                                    {% if prod.6 == 'bug' %}
                                        <span class="badge">Bug</span>
                                    {% endif %}
                                    </li>
                                {% endfor %}
                            {% endif %}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <input id="csrf_token" value="{{ csrf_token }}" hidden="hidden"/>

{% endblock %}

{% block js %}
    <script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/5.4.3/echarts.min.js"
            integrity="sha512-EmNxF3E6bM0Xg1zvmkeYD3HDBeGxtsG92IxFt1myNZhXdCav9MzvuH/zNMBU1DmIPN6njrhX1VTbqdJxQ2wHDg=="
            crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script type="text/javascript">
        let moveNode;
        let switch_status = 0;
        let add_index = 0;
        let sourceId
        let targetId

        $(function () {
            const observer = new MutationObserver(callback)
            // 配置观察选项
            const config = {childList: true, subtree: false};
            $("#kanban li").draggable({
                connectToSortable: "#storyTaskPool,#confirmAssignIng, #developing ,#doneAndTesting,#toBeRelease,#released",
                helper: "cut",
                revert: "invalid",
                start: function (event, ui) {
                    {#console.log("Item drag!");#}
                    {#console.log('draggable evt:', event)#}
                    {#console.log('droppable ui:', ui)#}
                    sourceId = ui.helper.parent()[0].id
                    {#console.log('droppable ui parent:', sourceId)#}
                    {#localStorage.setItem('sourceId', sourceId)#}
                    observer.observe(document.getElementById(sourceId), config)
                },
                drag: function (event, ui) {
                    let hoverTargetId = ui.helper.parent()[0].id
                    {#console.log('hoverTargetId>>>>:', hoverTargetId)#}
                    if (sourceId === 'storyTaskPool' || sourceId === 'confirmAssignIng' ||
                        sourceId === 'developing' || sourceId === 'doneAndTesting') {
                        $("#released").css("background-color", "red").css('opacity', 0.5)
                        if (hoverTargetId === 'released') {
                            layer.msg('invalid connect.')
                            alert("不能从此节点直接进行PROD发布")
                            {#console.log('invalid connect.........BBBBAAADDD')#}
                            window.location.reload()
                        }
                    }
                },
                stop: function (event, ui) {
                    let stopTargetId = ui.helper.parent()[0].id
                    $("#released").css("background-color", "white").css('opacity', 1)
                    observer.observe(document.getElementById(stopTargetId), config)
                    if (switch_status > 0) {
                        switch_status = 0
                    }
                }
            });

            $("#storyTaskPool,#confirmAssignIng, #developing ,#doneAndTesting,#toBeRelease,#released").sortable({
                connectWith: "#storyTaskPool,#confirmAssignIng, #developing ,#doneAndTesting,#toBeRelease,#released",
                revert: true,
                receive: function (event, ui) {
                    // Handle when an item is dropped into a column
                    {#console.log("Item dropped!");#}
                    {#console.log('droppable evt:', event)#}
                    targetId = event.target.id

                    {#console.log('droppable evt.target:', targetId)#}
                    //orginal

                }
            }).disableSelection();


        });

        function exportKanban() {
            const link = document.getElementById("exportKanbanLink")
            $.ajax({
                url: "{% url 'export_kanban' project_id=request.web.project.id %}?csrfmiddlewaretoke=" + $("#csrf_token").val(),
                type: "GET",
                {#dataType: "JSON",#}
                responseType: "Blob",
                success: function (res) {
                    console.log('exportKanban :', res);
                    {% comment %}  if (res) {
                          console.log('ok')
                          {#location.reload();#}

                      } else {

                      }{% endcomment %}
                },
                error: function (error) {
                    console.log('error', error)
                }

            })
        }

        function refreshKanban(someId) {
            console.log('refreshKanban :', someId);
            //task-34-1-0 表明task-34这个数据从sourceId所在位置1移动到了targetId所在位置0
            //后端会判定如果sourceId和targetId一致，则只更新缓存中的顺序。
            $.ajax({
                url: "{% url 'kanban_refresh' project_id=request.web.project.id %}",
                type: "POST",
                data: {
                    "sourceId": someId.sourceId,
                    "targetId": someId.targetId,
                    "moveNode": someId.moveNode,
                    "csrfmiddlewaretoken": $("#csrf_token").val()
                },
                dataType: "JSON",
                success: function (res) {
                    if (res.status) {
                        console.log('ok')
                        {#location.reload();#}

                    } else {

                    }
                }

            })
        }


        // 创建一个回调函数
        const callback = function (mutationsList) {

            for (let mutation of mutationsList) {
                if (mutation.type === 'childList') {
                    {#console.log('A child node has been moved.');#}
                    // 这里可以进一步处理，例如重新排序或更新UI等
                    // 获取被添加和移除的节点
                    const addedNodes = Array.from(mutation.addedNodes);
                    const removedNodes = Array.from(mutation.removedNodes);


                    // 处理被添加的节点
                    addedNodes.forEach(node => {
                        if (node.tagName.toLowerCase() === 'li' && targetId) {
                            let index = null

                            {#console.log('node.parentNode.children', node.parentNode.children)#}
                            {#console.log('node.parentNode.children.length', node.parentNode.children.length)#}

                            if (!node.parentNode || !node.parentNode.children) {
                                index = 0
                                add_index = index
                            }
                            if (node.parentNode && node.parentNode.children) {
                                {#console.log('a children:', node.parentNode.children)#}
                                {#console.log('a children length:', node.parentNode.children.length)#}
                                if (node.parentNode.children.length == 0) {
                                    index = 0
                                } else {
                                    index = Array.from(node.parentNode.children).indexOf(node);
                                    console.log('has child and index get:', index)
                                }

                                {#console.log('a children ele:', node.parentElement.children.item(index));#}
                            }
                            if (node.id) {

                                {#console.log('AParentNode', node.parentElement.id, 'Added:', node.textContent, 'ID:', node.id, 'Index:', index);#}
                                add_index = index
                                console.log('addIndex aft Added:', add_index)
                                // 立即调用 refreshKanban 函数以确保 add_index 已更新
                                if (sourceId && targetId && (sourceId !== targetId)) {
                                    //change position and order
                                    refreshKanban({
                                        sourceId: sourceId,
                                        targetId: targetId,
                                        moveNode: moveNode.id + "-" + moveNode.value + "-" + add_index
                                    })
                                    moveNode = null
                                } else if (sourceId && targetId && (moveNode.value != add_index)) {
                                    //change order
                                    let sourceDiv = document.getElementById(sourceId)
                                    let targetDiv = document.getElementById(targetId)
                                    {% comment %}  console.log('change order done sourceDiv', sourceDiv, 'targetDiv', targetDiv,
                                          'moveNode', moveNode, 'add_index', add_index){% endcomment %}
                                    refreshKanban({
                                        sourceId: sourceId,
                                        targetId: targetId,
                                        moveNode: moveNode.id + "-" + moveNode.value + "-" + add_index
                                    })
                                    moveNode = null
                                }
                                add_index = 0

                            }
                            // 进一步处理被添加的<li>节点
                        }
                    });

                    // 处理被移除的节点
                    removedNodes.forEach(node => {
                        if (node.tagName.toLowerCase() === 'li') {
                            let index = null

                            if (node) {
                                index = node.value
                            }

                            if (node.parentNode && node.parentNode.children) {
                                {#console.log('r children:', node.parentNode.children)#}
                                index = Array.from(node.parentNode.children).indexOf(node);
                                {#console.log('r children ele:', node.parentElement.children.item(index));#}
                            }
                            if (node.id) {

                                {#console.log('RParentNode', node.parentElement.id, 'Removed:', node.textContent, 'ID:', node.id, 'Index:', index);#}
                                if (switch_status == 0) {
                                    moveNode = node
                                }
                                switch_status = 1

                            }
                            // 进一步处理被移除的<li>节点
                        }
                    });

                }
            }
        };

        const grabItems = document.querySelectorAll('.grab-item');

        // 遍历所有具有 grab-item 类的 li 元素
        grabItems.forEach(function (item) {
            // 添加鼠标点击事件监听器
            item.addEventListener('mousedown', function () {
                this.style.cursor = 'grabbing';
            });

            // 添加鼠标释放事件监听器
            item.addEventListener('mouseup', function () {
                this.style.cursor = 'grab';
            });

            // 添加鼠标离开事件监听器
            item.addEventListener('mouseleave', function () {
                this.style.cursor = 'grab';
            });
        });


    </script>

{% endblock %}